<?php

namespace Common\Model;
use Think\Model;

// 合作者模型
Class PlatformModel extends Model {

	protected $_auto = array(
		array('create_time', NOW_TIME, self::MODEL_INSERT),
		array('update_time', NOW_TIME, self::MODEL_BOTH),
		array('app_id', 'ctAppId', self::MODEL_INSERT, 'callback'),
		array('app_secret', 'ctAppSecret', self::MODEL_INSERT, 'callback'),
		array('status', '1', self::MODEL_BOTH),
	);

	public function ctAppId() {
		$id = $this->getField('max(app_id)');
		$id = $id ? $id + 1 : sprintf("66%s%03d", date('Y'), $id);
		return $id;
	}

	public function ctAppSecret() {
		return md5(uniqid(mt_rand(), true));
	}

	public function getByAppId($app_id = '') {
		if (!$app_id) {
			return;
		}

		$map['app_id'] = $app_id;
		return $this->where($map)->find();
	}

	public function _before_write(&$data, $options) {
		$data['games'] && $data['games'] = implode(',', $data['games']);
		$data['data'] && $data['data'] = serialize($data['data']);
	}

	public function _after_find(&$result, $options) {
		if ($result) {
			$result['data'] = unserialize($result['data']);
			$result['games'] = explode(',', $result['games']);
		}
	}

}